 <script setup lang="ts">
import { computed,  ref, reactive, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '../../utils/request';

const dialogFormVisible = ref(false)

const GlobalIndex = ref(-1)

const name = ref('')

const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(5)

// 声明一个全局变量来存储选中行的ID
const selectedIds = ref<number[]>([]);
interface User {
  id: number; // 或其他适当的数据类型
  date: string;
  name: string;
  address: string;
  
}

let tableData = ref<Array<User>>([
 
])
const now =  reactive(new Date());
let form = reactive({
  date: now.toISOString().substring(0, 10),
  name: '',
  address: '',
})

const handeAdd = () => {
    form = reactive({
      date: now.toISOString().substring(0, 10),
      name: '',
      address: '',
    })
    dialogFormVisible.value = true
}
const save = () => {
  // if(GlobalIndex.value >=0){
  // console.log(GlobalIndex.value)
  //  tableData.value[GlobalIndex.value] = form
  //  GlobalIndex.value = -1
  // }                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        
  // else{
  //   tableData.value.push(form)
  // }
   request({
    url: form.id ? '/user/update' : '/user/save',
    method: form.id ? 'put' : 'post', // 根据id是否存在来判断是put还是post
    data: form
   }).then((res:any) => {
    if(res.code == 200){
      ElMessage({
      message: '操作成功',
      type: 'success',
     })
      load();
      dialogFormVisible.value = false
    }else{
      ElMessage.error(res.msg)
    } 
})
}
const handleEdit = (row: any, index: number) => {
  const newobj = Object.assign({}, row)
  form = reactive(newobj)
  GlobalIndex.value = index
  dialogFormVisible.value = true
}

const handleDelete = (id: number) => {
  ElMessageBox.confirm('是否删除该条数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // tableData.value.splice(index, 1); // 删除指定索引的数据
    request.delete('/user/delete?id='+id).then((res:any) => {
        if(res.code == 200){
          ElMessage.success('操作成功')
          load();
        }else{
          ElMessage.error(res.msg)
        }
    })
    ElMessage({
      type: 'success',
      message: '删除成功!'
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    });
  });
};

const handleSelectionChange =  (rows: User[]) => {
    selectedIds.value = rows.map(item => item.id);
}

const delBatch = () => {
    if (selectedIds.value.length === 0) {
        ElMessage.warning('请先选择要删除的数据');
        return;
   }
    ElMessageBox.confirm('是否删除所选的所有数据?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // tableData.value.splice(index, 1); // 删除指定索引的数据
    request.delete('/user/deleteAll',{
        data: selectedIds.value,
        method: 'delete',
    }
    ).then((res:any) => {
        console.log(selectedIds.value)
        if(res.code == 200){
          ElMessage.success('操作成功')
          load();
           // 清空选中行ID
        selectedIds.value = [];
        }else{
          ElMessage.error(res.msg)
        }
    })
    ElMessage({
      type: 'success',
      message: '删除成功!'
    });
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    });
  });
}

const exportExcel = () => {
    if (! selectedIds.value.length ) {
      window.open('http://localhost:8082/user/export'+'?name='+name.value)
   }else {      // [1,2,3] => '1,2,3'
    let idStr = selectedIds.value.join(',')
    console.log(idStr)
    window.open('http://localhost:8082/user/export' + '?ids=' + idStr)
  }
}

const handleimport = (res:any,file:File,fileList:File[]) => {
  if(res.code == 200){
      ElMessage.success('导入成功')
      load();
  }else{
    ElMessage.error(res.msg)
  }
}
// 搜索关键字状态管理
const searchValue = ref('');

// 定义计算属性，根据搜索关键字过滤表格数据

let filterTableData = computed(() =>
  tableData.value.filter(
    (data) =>
      !searchValue.value ||
      data.name.toLowerCase().includes(searchValue.value.toLowerCase())
  )
);

// 监听 searchValue 的变化
watch(name, (newValue, oldValue) => {
  console.log('searchValue changed', newValue, oldValue);
  if (! name.value) {
    load();
  } 
});
// 搜索功能的实现
// const search = () => {
//   searchValue.value = name.value;
//   console.log(searchValue.value); // 更新搜索关键字为输入框的值
// };

// const load = () => {
//   let start = (pageNum.value - 1)*pageSize.value;
//   // 获取数据
//     request.get('user/page?name='+name.value+'&start='+start+'&pageSize='+pageSize.value).then((res) => {
//     console.log(res);
//     tableData.value = res.data.list;
//      //total.value = Math.ceil(res.data.total / pageSize.value);
//      total.value = res.data.total;
//     // console.log(tableData);
//   });
// }; 

const load = () => { 
// 分页查询
 request.get('/user/page', {
        params: {
          pageNum: pageNum.value,
          pageSize: pageSize.value,
          name: name.value
        }
      
      }).then((res:any) => {
        console.log(res);
        tableData.value = res.data.records;
        total.value = res.data.total;
        console.log(tableData);
      })
    }
load()
</script>
<template>
<div>
    <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>用户列表</span>
      </div>
    </template>
    <!-- Element UI Input 组件，用于输入搜索名称 -->
    <el-input style="width:300px" placeholder="请输入名称" v-model="name" clearable></el-input>

    <!-- Element UI 主题样式按钮，点击后执行搜索动作 -->
    <el-button type="primary" @click="load" style="margin-left:5px">搜索</el-button>
    <el-button type="primary" @click="handeAdd" >新增数据</el-button>
    <el-button type="danger"  style="margin-left:5px" @click="delBatch" >批量删除</el-button>
    <el-button type="info" @click="exportExcel" >批量导出</el-button>
    <el-upload action="http://localhost:8082/user/import" style="display: inline-block; margin:2px 5px ;"  @success="handleimport"  :show-file-list="false">
      <el-button type="primary"  >批量导入</el-button>
    </el-upload>
    <div style="margin:0 10px">
    <el-table :data="filterTableData" style="width: 100%" 
    :header-cell-style="{ 'background-color': 'aliceblue' ,'color':'#666'} "
    @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="55" align = 'center' />
    <el-table-column prop="date" label="日期" sortable  width="180" align = 'center' />
    <el-table-column prop="name" label="姓名" width="180" align = 'center'/>
    <el-table-column prop="address" label="地址" align = 'center'/>
    <el-table-column  align = 'right'>
        <template #default="scope">
        <el-button link type="primary" size="small" @click="handleEdit(scope.row,scope.$index)"
          >编辑</el-button>
        <el-button link type="danger" size="small" @click.prevent="handleDelete(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
   </el-table>
    <div style = "margin: 15px 0">
      <el-pagination background layout="sizes, prev, pager, next,total,jumper" 
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :page-sizes="[1,3,5,10]"
      :total="total" 
      @size-change="load"
      @current-change="load"/>
    </div>
    </div>

    <el-dialog v-model="dialogFormVisible" title="信息"  width="50%"> 
    <el-form :model="form" label-width="100px" style="padding-right: 30px;" >
      <el-form-item label="日期" >
        <el-date-picker v-model="form.date" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" style="width: 100%"/>
        <!-- <el-input v-model="form.date" autocomplete="off" /> -->
      </el-form-item>
      <el-form-item label="姓名" >
        <el-input v-model="form.name" autocomplete="off" />
      </el-form-item>
      <el-form-item label="地址" >
        <el-input v-model="form.address" autocomplete="off" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="save">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>

  </el-card>

</div>

</template>